package day15.ZH;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Shou01 {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(10000);
        ThreadPoolExecutor pool = new ThreadPoolExecutor(
                3,//核心线程
                10,//最大线程
                60,//等待时间
                TimeUnit.SECONDS,//时间单位
                new ArrayBlockingQueue<>(5),//阻塞队列允许几个
                Executors.defaultThreadFactory(),//创建线程的方式
                new ThreadPoolExecutor.AbortPolicy()//任务拒绝策略
        );
        while (true) {
            Socket accept = ss.accept();
            ThreadSocket t = new ThreadSocket(accept);
//            new Thread(t).start(); 线程池已经创建了 线程就不需要创建了
            pool.submit(t);
        }

    }
}

class ThreadSocket implements Runnable {
    private Socket acceptSocket;

    public ThreadSocket(Socket accept) {
        this.acceptSocket = accept;
    }

    @Override
    public void run() {
        BufferedOutputStream bos = null;
        try {
            //        网络中的流,从客户端读取数据
            BufferedInputStream bis = new BufferedInputStream(acceptSocket.getInputStream());
//        本地流,把数据写到本地,实现存储
            bos = new BufferedOutputStream(new FileOutputStream("H:\\itheima\\bb\\" + UUID.randomUUID().toString() + ".png"));
            int b;
            while ((b = bis.read()) != -1) {
                bos.write(b);
            }
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(acceptSocket.getOutputStream()));
            bw.write("上传成功");
            bw.newLine();
            bw.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (acceptSocket != null) {
                try {
                    acceptSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        }
    }
}